import { array } from "js-md5";

class Socket {
    constructor (props) {
        this.websocket = null;
        this.timeoutObj =null;
        this.serverTimeoutObj = null;
        this.lockReconnect= false;
        this.init(props)
    }
    init (param) {
        
        try {
            this.websocket = new WebSocket(param.url);
            
        }catch (err){
            console.log(err)
        }
        this.websocket.onopen = ()=>{
            console.log('尝试连接...')
            this.websocket.send('发送数据...')
           
        }
        this.websocket.onerror = ()=>{
            this.reconnect()
        }
        this.websocket.onmessage = (evt) =>{
            param.callback(evt.data)
            this.heartCheck()
        }
        
    }
    heartCheck () {
        if(this.websocket.readyState !=1){
            this.reconnect()
        }else{
            this.timeoutObj && clearTimeout(this.timeoutObj);
            this.timeoutObj = setTimeout(()=>{
                this.websocket.send("123456789");
            },3000)
        }
      

    }
    reconnect () {
        if(this.lockReconnect ) {
            return;
        }
        this.lockReconnect = true;
        this.serverTimeoutObj  && clearTimeout( this.serverTimeoutObj );
        this.serverTimeoutObj = setTimeout(()=>{
            this.init()
            this.lockReconnect = false;
        },1000)

        
    }
    close () {
        console.log('关闭连接')
        this.websocket.close()
    }

}

export default Socket


